package com.demo.search;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class Searcher {

	public static void main(String[] args) throws Exception {
		
		if (args.length != 2) {
			throw new IllegalArgumentException("Usage: Java" + Indexer.class.getName() + " <index dir> <query dir>");
		}
		String indexDir = args[0];
		String query = args[1];
		
		search(indexDir, query);
		
		//System.out.println("Indexing " + numIndexed + " fileds took " + ( end - start) + " milliseconds");
	}
	
	public static void search(String indexDir, String q) throws IOException, ParseException {
		
		Directory dir = FSDirectory.open(new File(indexDir));
		IndexReader indexReader = IndexReader.open(dir);
		
		// 索引快照
		IndexReader newReader = IndexReader.openIfChanged(indexReader);
		if (newReader != null) {
			indexReader.close();
			indexReader = newReader;
		}
		IndexSearcher searcher = new IndexSearcher(indexReader);
		
		QueryParser parser = new QueryParser(Version.LUCENE_36, "contents", new StandardAnalyzer(Version.LUCENE_36));
		Query query = parser.parse(q);
		long start = System.currentTimeMillis();
		TopDocs hits = searcher.search(query, 10);
		long end = System.currentTimeMillis();
		System.err.println("Found " + hits.totalHits + " document(s) (in " + (end - start) + " milliseconds) that matched query '" + q + "'");
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			//
			Document doc = searcher.doc(scoreDoc.doc);
			// 取得结果评分
			Explanation explanation = searcher.explain(query, scoreDoc.doc);
			System.out.println(doc.get("fullpath"));
			System.out.println(explanation.toString());
		}
		searcher.close();
	}
}
